#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: 高建平
# @description: 
#

from fastapi.staticfiles import StaticFiles
from loguru import logger
from fastapi import FastAPI
from dotenv import load_dotenv
from pathlib import Path
import os


from app.providers import app_provider
from app.providers import logging_provider
from app.providers import exception_provider
from app.providers import route_provider
from app.providers import swagger_provider
from config.bootstrap import settings
from config.settings import FASTAPI_PROFILE,DEFAULT_FASTAPI_PROFILE



def create_app() -> FastAPI:
    # 加载环境变量
    logger.info("App start env {}",os.getenv(FASTAPI_PROFILE,DEFAULT_FASTAPI_PROFILE))
    load_dotenv(dotenv_path=Path('.env.'+os.getenv(FASTAPI_PROFILE,DEFAULT_FASTAPI_PROFILE)),verbose=True)
    app = FastAPI(debug=settings.DEBUG,title=settings.NAME,description=settings.NAME,
        docs_url=None, redoc_url=None)
    app.mount("/static", StaticFiles(directory="app/static"), name="static")
    
    logger.info("App initializing")
    register(app, logging_provider)
    register(app, swagger_provider)
    register(app, exception_provider)
    register(app, app_provider)
    boot(app, route_provider)
    
    @app.on_event("startup")
    def startup():
        logger.info("App startup")
        
    @app.on_event("shutdown")
    def shutdown():
        logger.info("App shutdown")
    return app


def register(app, provider):
    '''
     服务相关组件
    '''
    logger.info(provider.__name__ + ' registering')
    provider.register(app)


def boot(app, provider):
    '''
     路由
    '''
    logger.info(provider.__name__ + ' booting')
    provider.boot(app)

app = create_app()